package com.atguigul.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigul.gulimall.auth.feign.MemberFeignService;
import com.atguigu.vo.MemberRespVo;
import com.atguigul.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

//处理社交登录申请
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "716dcc2f5e4b6b39b0e25299e01b107efb5ffff4b3fceaf4de3f3608af1487e7");
        map.put("client_secret", "6c839aa6e9887ceb2ee00f54bda159a7e7436ca95a3c6227a7938510898f89d3");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("code", code);
        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());

        //2、处理
        if (response.getStatusLine().getStatusCode() == 200) {
            // todo 授权成功处理
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道是谁登录，然后可以根据是否是第一次登录，决定是直接登录还是登录加注册。
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            if (oauthlogin.getCode()==0){
                MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });
//                System.out.println("登录成功，用户信息：" + data);
                log.info("登录成功，用户：{}",data.toString());
                session.setAttribute(AuthServerConstant.LOGINUSER,data);
                return "redirect:http://gulimall.com";

            }else{
                return "redirect:http://auth.gulimall.com.login.html";
            }

        } else {
            // todo 授权失败处理，重新登录
            return "redirect:http://auth.gulimall.com.login.html";

        }

    }


}